import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

/** ****/
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // set page title
  document.title = to.meta.title || '报价系统'
  // 显示这两个页面的tab导航栏
  if (to.path == '/home' || to.path == '/demand' || to.path == '/product' || to.path == '/user') {
    store.dispatch('sync/setThisPage', true)
  } else {
    store.dispatch('sync/setThisPage', false)
  }
  // 多页面，前进刷新 后退不刷新
  // if (from.path.indexOf('Rank') > -1 && to.path == '/businessOpportunity') {
  //   to.meta.keepAlive = false
  // } else {
  //   if(to.path == '/businessOpportunity'){
  //     to.meta.keepAlive = true
  //   }
  // }

  const hasTenantId = localStorage.getItem('tenantId')
  if (!hasTenantId) {
    await store.dispatch('user/getChannelinfo')
  }
  // next()
  // return
  // token 一天已过期
  // const code = location.href?.split('code=')[1]?.split('&')[0]
  // alert(code)
  // return
  const hasToken = getToken()
  if (!hasToken) {
    const code = location.href?.split('code=')[1]?.split('&')[0]
    if (code) {
      const params = { code, tenantId: localStorage.getItem('tenantId') }
      await store.dispatch('user/login', params)
      next()
    } else {
      next()
    }
  } else {
    const deptId = store.getters['userInfo'].deptId
    if (!deptId) {
      const err = await store.dispatch('user/getUserInfo')
      if (err?.code == 401) {
        await store.dispatch('user/resetToken')
        location.reload()
      } else {
        next()
      }
    } else {
      next()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
